package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {


    @Autowired
    private AlbumInfoFeignClient albumFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据专辑ID查询专辑详情信息
     * 汇总专辑详情页面渲染所有四项数据
     * - albumInfo：当前专辑信息（已完成）
     * - albumStatVo：专辑统计信息（已完成）
     * - baseCategoryView：专辑分类信息（已完成）
     * - announcer：专辑主播信息
     *
     * @param albumId
     * @return
     */
    @Override
    public Map<String, Object> getItem(Long albumId) {
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
                if (!bloomFilter.contains(albumId)) {
                    log.info("数据不存在于布隆过滤器中，返回空值或做其他处理: {}", albumId);
                      // 数据不存在，直接返回空值或做其他处理
                    throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
                }
        //多线程环境下进行并发读写hashMap线程不安全替换为ConcurrentHashMap
        Map<String, Object> mapResult = new ConcurrentHashMap<>();
        //1.远程调用专辑服务获取专辑基本信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑信息为空");
            mapResult.put("albumInfo", albumInfo);
            return albumInfo;
        }, threadPoolExecutor);

        //2.远程调用专辑服务获取专辑统计信息
        CompletableFuture<Void> statCompletableFuture = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo, "专辑统计信息为空");
            mapResult.put("albumStatVo", albumStatVo);
        }, threadPoolExecutor);

        //3.获取到专辑后，得到专辑对应三级分类ID，获取分类信息
        CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            Assert.notNull(baseCategoryView, "分类信息为空");
            mapResult.put("baseCategoryView", baseCategoryView);
        }, threadPoolExecutor);


        //4.获取到专辑后，得到专辑对应主播ID，获取主播信息
        CompletableFuture<Void> userInfoCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVoByUserId(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo, "主播信息为空");
            mapResult.put("announcer", userInfoVo);
        }, threadPoolExecutor);

        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                baseCategoryViewCompletableFuture,
                statCompletableFuture,
                userInfoCompletableFuture
        ).join();
        return mapResult;
    }
}
